package cn.steel.service.impl;

import cn.steel.domain.entity.SupplierInfo; import cn.steel.domain.entity.User; import cn.steel.mapper.RegisterMapper; import cn.steel.mapper.SupplierInfoMapper; import cn.steel.service.RegisterService; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service @Transactional(rollbackFor = Exception.class) @RequiredArgsConstructor public class RegisterServiceImpl implements RegisterService {

    private static final Logger logger = LoggerFactory.getLogger(RegisterServiceImpl.class);

    private final RegisterMapper registerMapper;
    private final SupplierInfoMapper supplierInfoMapper;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public void register(User user) {
        // 加密密码
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);

        // 插入 user 表
        logger.info("插入用户记录: username={}", user.getUsername());
        registerMapper.insert(user);
        logger.info("用户插入成功: id={}, username={}", user.getId(), user.getUsername());

        // 如果用户角色是 SUPPLIER，初始化 supplier_info
        if ("SUPPLIER".equals(user.getRole())) {
            if (user.getId() == null) {
                logger.error("用户ID为空，无法初始化 supplier_info: username={}", user.getUsername());
                throw new IllegalStateException("用户ID为空，无法初始化 supplier_info");
            }

            logger.info("用户角色为 SUPPLIER，开始初始化 supplier_info: user_id={}", user.getId());
            SupplierInfo supplierInfo = new SupplierInfo();
            supplierInfo.setUserId(user.getId());
            supplierInfo.setCompany(user.getCompany() != null ? user.getCompany() : "默认公司");
            supplierInfo.setPhone(user.getPhone() != null ? user.getPhone() : "未提供");
            supplierInfo.setAddress(user.getAddress() != null ? user.getAddress() : "未提供");
            supplierInfo.setDescription("新供应商默认简介");
            supplierInfo.setCreateTime(LocalDateTime.now());
            initializeSupplierInfo(supplierInfo);
            logger.info("supplier_info 初始化成功: user_id={}", user.getId());
        }
    }

    @Override
    public boolean existsByUsername(String username) {
        return registerMapper.countByUsername(username) > 0;
    }

    @Override
    public void initializeSupplierInfo(SupplierInfo supplierInfo) {
        if (supplierInfo.getUserId() == null) {
            logger.error("SupplierInfo.userId 为空，无法插入 supplier_info");
            throw new IllegalArgumentException("SupplierInfo.userId 不能为空");
        }
        supplierInfoMapper.insertSupplierInfo(supplierInfo);
    }

}